package com.dctp.ems.controller;

import com.dctp.common.controller.BaseController;
import com.dctp.common.utils.DateUtil;
import com.dctp.common.vo.JsonResult;
import com.dctp.common.vo.PageResult;
import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Path("/notice")
public class NoticeController extends BaseController {


    public void list() {
        int page = getInt("currentPage", 1);
        int pageSize = getInt("pageSize", 10);
        String title = getPara("title", "");
        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> params = new ArrayList<>();
        if (!title.isEmpty()) {
            where.append(" AND title LIKE ?");
            params.add('%' + title + '%');
        }

        String select = "SELECT * ";
        String from = "FROM dctp_notice " + where + " ORDER BY id DESC";
        var p = Db.paginate(page, pageSize, select, from, params.toArray());
        renderJson(JsonResult.successWithData(
            new PageResult<>(p.getList(), p.getTotalRow(), pageSize, page)
        ));
    }


    @Before(Tx.class)
    public void add() {
        Record body = jsonBody();
        LocalDateTime now = DateUtil.now();
        body.set("create_time",now)
                .set("update_time",now);
        if (!Db.save("dctp_notice", body)) {
            throw new RuntimeException("新增公告失败");
        }
        renderJson(JsonResult.success());
    }


    @Before(Tx.class)
    public void update() {
        Integer id = getParaToInt(0);
        if (id == null) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }
        Record body = jsonBody();
        if (body.getColumns().isEmpty()) {
            renderJson(JsonResult.failWithMessage("无有效字段"));
            return;
        }
        body.set("id", id)
            .set("update_time", DateUtil.now());
        boolean updated = Db.update("dctp_notice", body);
        if (!updated) {
            renderJson(JsonResult.failWithMessage("更新失败或记录不存在"));
            return;
        }
        renderJson(JsonResult.success());
    }

    @Before(Tx.class)
    public void delete() {
        Integer id = getParaToInt(0);
        if (id == null) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }
        int r = Db.update("DELETE FROM dctp_notice WHERE id=?", id);
        if( r == 0) {
            renderJson(JsonResult.failWithMessage("删除失败或记录不存在"));
        }
        renderJson(JsonResult.success());
    }
}
